﻿using ERP.WorkforceManage;
using ERP.WorkforceManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Volo.Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using ERP.ERPModels.WorkforceManage;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace ERP.Web.Controllers
{
    /// <summary>
    /// 排班计划控制器
    /// </summary>
    public class SchedulingPlanController : AbpController
    {
        private readonly ISchedulingPlanService _schedulingPlanService;
        private readonly IRepository<SchedulingPlan, int> _schedulingPlanRepository;
        private readonly ITeamService _teamService;
        private readonly ILogger<SchedulingPlanController> _logger;

        public SchedulingPlanController(
            ISchedulingPlanService schedulingPlanService,
            IRepository<SchedulingPlan, int> schedulingPlanRepository,
            ITeamService teamService,
            ILogger<SchedulingPlanController> logger)
        {
            _schedulingPlanService = schedulingPlanService;
            _schedulingPlanRepository = schedulingPlanRepository;
            _teamService = teamService;
            _logger = logger;
        }

        /// <summary>
        /// 排班计划管理页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取排班计划列表
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetList([FromBody] SchedulingPlanGetListInputDto input)
        {
            try
            {
                var result = await _schedulingPlanService.GetListAsync(input);
                return Json(new { code = 0, msg = "success", data = result.Items, count = result.TotalCount });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取排班计划列表失败");
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 获取排班计划详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Get(int id)
        {
            try
            {
                var result = await _schedulingPlanService.GetAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取排班计划详情失败，ID: {Id}", id);
                return Json(new { success = false, msg = ex.Message });
            }
        }

        /// <summary>
        /// 创建排班计划
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] CreateSchedulingPlanDto input)
        {
            try
            {
                _logger.LogInformation("创建排班计划，输入数据: {Input}", JsonSerializer.Serialize(input));
                var result = await _schedulingPlanService.CreateAsync(input);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建排班计划失败，输入数据: {Input}", JsonSerializer.Serialize(input));
                return Json(new { success = false, msg = ex.Message });
            }
        }

        /// <summary>
        /// 更新排班计划
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Update(int id, [FromBody] SchedulingPlanDto input)
        {
            try
            {
                // 校验输入
                if (input == null)
                {
                    return Json(new { success = false, msg = "无效的输入数据" });
                }
                
                // 确保ID一致
                input.Id = id;
                
                _logger.LogInformation("更新排班计划，ID: {Id}, 输入数据: {Input}", id, JsonSerializer.Serialize(input));
                
                // 处理特殊情况
                if (input.ShiftSystem == "白班")
                {
                    input.WorkShiftSystem = "";
                    input.DayCount = null;
                }
                else if (input.ShiftSystem == "两班倒" || input.ShiftSystem == "三班倒")
                {
                    if (input.WorkShiftSystem != "按天")
                    {
                        input.DayCount = null;
                    }
                }
                
                await _schedulingPlanService.UpdateAsync(id, input);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新排班计划失败，ID: {Id}, 输入数据: {Input}", id, input != null ? JsonSerializer.Serialize(input) : "null");
                return Json(new { success = false, msg = "更新失败: " + ex.Message });
            }
        }

        /// <summary>
        /// 删除排班计划
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _schedulingPlanService.DeleteAsync(id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除排班计划失败，ID: {Id}", id);
                return Json(new { success = false, msg = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除排班计划
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> BatchDelete([FromBody] List<int> ids)
        {
            try
            {
                foreach (var id in ids)
                {
                    await _schedulingPlanService.DeleteAsync(id);
                }
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除排班计划失败，IDs: {Ids}", string.Join(",", ids));
                return Json(new { success = false, msg = ex.Message });
            }
        }
        
        /// <summary>
        /// 获取排班计划关联的班组
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetTeams(int id)
        {
            try
            {
                // 从服务获取排班计划详情
                var schedulingPlan = await _schedulingPlanService.GetAsync(id);
                
                // 确保TeamIds不为null，如果为空则返回空数组
                if (schedulingPlan.TeamIds == null || !schedulingPlan.TeamIds.Any())
                {
                    return Json(new { code = 0, msg = "success", data = new List<object>() });
                }
                
                // 获取班组信息
                var teams = new List<object>();
                foreach (var teamId in schedulingPlan.TeamIds)
                {
                    try
                    {
                        var team = await _teamService.GetAsync(teamId);
                        if (team != null)
                        {
                            teams.Add(new
                            {
                                id = team.Id,
                                teamNumber = team.TeamNumber,
                                teamName = team.TeamName,
                                teamType = team.TeamType,
                                descr = team.Descr
                            });
                        }
                    }
                    catch
                    {
                        // 如果获取某个班组失败，继续获取下一个
                        continue;
                    }
                }
                
                return Json(new { code = 0, msg = "success", data = teams });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取排班计划关联班组失败，ID: {Id}", id);
                return Json(new { code = 0, msg = "success", data = new List<object>() });
            }
        }
    }
}
